<template>
  <div class="app-container">
    <div class="search_container_warp">
      <el-form class="search_container" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="addFn" v-if="!statusFlag"
            >新增试题</el-button
          >
        </el-form-item>
        <el-form-item>
          <Custom-Upload
            v-if="!statusFlag"
            @set-file="questionUploadFn"
            :showFileFlag="false"
            btnName="导入"
            fileType="xlsx"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="!statusFlag"
            type="primary"
            @click="downloadTemplateFn"
          >
            下载模版
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="form_card_warp">
      <el-form ref="queryFormRef" :model="formData" :inline="true">
        <el-row :gutter="32">
          <!-- 一行显示试卷相关信息 -->
          <el-col :span="6">
            <el-form-item prop="testPaperName" label="试卷名称：">
              {{ formData.name }}
              <!-- <el-input v-model="formData.name" readonly /> -->
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="group" label="比赛组别：">
              {{ formData.matchGroupName }}
              <!-- <el-input v-model="formData.matchGroupName" readonly /> -->
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="testQuestionsNumber" label="试题数量：">
              {{ formData.questionNumber }}
              <!-- <el-input v-model="formData.questionNumber" readonly /> -->
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="single" label="单选分值：">
              {{ formData.score1 }}
              <!-- <el-input v-model="formData.score1" readonly /> -->
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="many" label="多选分值：">
              {{ formData.score2 }}
              <!-- <el-input v-model="formData.score2" readonly /> -->
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="judge" label="判断分值：">
              {{ formData.score3 }}
              <!-- <el-input v-model="formData.score3" readonly /> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        class="customTableClass"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
      >
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column
          label="题型"
          prop="questionTypeName"
          align="center"
          min-width="80"
        />
        <el-table-column
          label="题目"
          prop="questionContent"
          align="center"
          min-width="220"
        />
        <el-table-column
          label="答案"
          prop="answer"
          align="center"
          width="100"
        />
        <el-table-column
          label="选项A"
          prop="optionA"
          align="center"
          width="100"
        />
        <el-table-column
          label="选项B"
          prop="optionB"
          align="center"
          width="100"
        />
        <el-table-column
          label="选项C"
          prop="optionC"
          align="center"
          width="100"
        />
        <el-table-column
          label="选项D"
          prop="optionD"
          align="center"
          width="100"
        />
        <el-table-column
          label="更新信息"
          prop="updateUsername"
          align="center"
          min-width="110"
        >
          <template #default="scope">
            {{ (scope.row.updateUsername || "") + " " + scope.row.updateDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="optionF" align="center" width="100">
          <template #default="scope">
            <el-icon class="editIconClass">
              <Edit @click="editFn(scope.row)" />
            </el-icon>
            <el-icon class="deleteIconClass" v-if="!statusFlag">
              <Delete @click="handleDelete(scope.row.id)" />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      modal-class="maxHeightClass"
      :close-on-click-modal="false"
      v-model="dialog.visible"
      :title="dialog.title"
      width="1100px"
      draggable
      align-center
      @close="closeDialog"
    >
      <add-test-questions
        v-if="dialog.visible"
        :disabled="statusFlag"
        :itemObj="itemObj"
        :testPaperName="formData.name"
        :group="formData.matchGroupName"
        :paperId="queryParams.paperId"
        @submit="submitFn"
        @close="closeDialog"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { computeHeiht } from "@/utils/index";
import {
  getTestQuestionsList,
  questionDelete,
  downloadTemplate,
  questionUpload,
} from "@/api/examPaperManagement";
import {
  ItemPageVO,
  ItemPageVO2,
  Options,
  ItemForm,
} from "@/api/examPaperManagement/types";

const router = useRouter();
const route = useRoute();

defineOptions({
  name: "QuestionManagement",
  inheritAttrs: false,
});

const options = ref<Options[]>([]);
const queryFormRef = ref(ElForm);
const dataList = ref<ItemPageVO2[]>([]);
const originalDataList = ref<ItemPageVO2[]>([]);

const loading = ref(false);

const formData = reactive<ItemForm>({
  name: "",
  matchGroupName: "",
  paperId: "",
});
const queryParams = reactive<ItemForm>({});

const itemObj = reactive<ItemPageVO2>({});
const statusFlag = computed(() => {
  console.log("ccccccccccccccc", route.query.status);
  return route.query.status === "已审核";
});
const dialog = reactive({
  title: "",
  visible: false,
});

// 题目类型
options.value = [
  {
    label: "单选题",
    value: 1,
  },
  {
    label: "多选题",
    value: 2,
  },
  {
    label: "判断题",
    value: 3,
  },
];

/** 查询 */
function handleQuery() {
  loading.value = true;
  getTestQuestionsList(queryParams)
    .then(({ data }) => {
      data.forEach((v) => {
        v.questionTypeName = options.value.find(
          (j) => v.questionType === j.value
        )?.label;
      });
      dataList.value = data;
      originalDataList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

function addFn() {
  itemObj.id = undefined;
  itemObj.questionType = 1;
  itemObj.questionContent = "";
  itemObj.answer = "";
  itemObj.optionA = "";
  itemObj.optionB = "";
  itemObj.optionC = "";
  itemObj.optionD = "";
  itemObj.analysis = "";
  // itemObj.optionE = "";
  // itemObj.optionF = "";
  itemObj.questionFile = "";
  dialog.visible = true;
  dialog.title = "新增试题";
}
function editFn(data: ItemPageVO2 = {}) {
  itemObj.id = data.id;
  itemObj.questionType = data.questionType;
  itemObj.questionContent = data.questionContent;
  itemObj.answer = data.answer;
  itemObj.optionA = data.optionA;
  itemObj.optionB = data.optionB;
  itemObj.optionC = data.optionC;
  itemObj.optionD = data.optionD;
  itemObj.analysis = data.analysis;
  // itemObj.optionE = data.optionE;
  // itemObj.optionF = data.optionF;
  itemObj.questionFile = data.questionPhoto;

  dialog.visible = true;
  dialog.title = "编辑试题";
}

/** 删除 */
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除数据项?", "确认删除", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "error",
  }).then(() => {
    loading.value = true;

    questionDelete(id)
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  });
}
function goBack() {
  router.back();
  // router.replace({ path: "/examPaperManagement/index" });
}

function submitFn() {
  closeDialog();
  handleQuery();
}
function closeDialog() {
  dialog.visible = false;
}
function questionUploadFn(data: any) {
  let params = new FormData();
  params.append("id", queryParams.paperId || "");
  params.append("file", data);
  loading.value = true;
  questionUpload(params)
    .then(() => {
      ElMessage.success("导入成功");
      handleQuery();
    })
    .finally(() => {
      loading.value = false;
      handleQuery();
    });
}
function downloadTemplateFn() {
  downloadTemplate().then((res) => {
    const blob = new Blob([res.data], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const downloadLink = document.createElement("a");
    downloadLink.href = url;
    downloadLink.download = "questions_import_template.xlsx";
    downloadLink.click();
  });
}

onMounted(() => {
  const query: ItemForm = route.query;
  queryParams.paperId = query.id + "" || "";
  formData.name = query.name;
  formData.matchGroupName = query.matchGroupName;
  formData.questionNumber = query.questionNumber;
  formData.score1 = query.score1;
  formData.score2 = query.score2;
  formData.score3 = query.score3;

  handleQuery();
  computeHeiht(180);
});
</script>
